package givenchy

class ApiController {
    def cacheService
    def tokenService
    def authenticateService


    def beforeInterceptor = {
           log.info request.getHeader("User-Agent")
           def agent = request.getHeader("User-Agent")
           if (agent.indexOf("H2O") < 0) {
               return false
           }
    }
    //Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13

    def  login = {
          if (params.u && params.p) {
                // 这里需要验证一下用户和密码
                def user = User.findByUsernameAndEnabled(params.u , true)
                if (user) {
                        if (user.passwd == authenticateService.encodePassword(params.p)) {
                             
                            def token = tokenService.build(user.id.toString()) 
                            return render(
                                contentType:"text/json",
                                text : """{"success":true , "token": "${token}"}""") 
                        }
                } 
            } 
            // 用户名和密码 不存在
            return render(
            contentType:"text/json",
            text : '{"success":false}')  
            
    }
    // 在api做一个客户端agnet验证，，，，
    def index = { 
        //验证客户身份,通过token值认证，认证识别客户端可以再次申请一个，然后再来获取网址
        if (!params.t || !tokenService.verify(params.t)) { 
                return render(
                    contentType:"text/json",
                    text : '{"token":""}')  
        }
        def user = tokenService.user(params.t)
        if (!user.enabled) {
               return render(
                    contentType:"text/json",
                    text : '{"token":""}')   
        }

    // 获得客户端ip

        
       if (!params.ip) {
            String ip = request.getHeader("x-forwarded-for");       
            if(!ip   || "unknown".equalsIgnoreCase(ip)) {       
                ip = request.getHeader("Proxy-Client-IP");       
            }       
            if(!ip || "unknown".equalsIgnoreCase(ip)) {       
                ip = request.getHeader("WL-Proxy-Client-IP");       
            }       
            if(!ip || "unknown".equalsIgnoreCase(ip)) {       
                ip = request.getRemoteAddr();       
            }       
            params.ip = ip; 
        }

        // 检查ip质量
        if (!params.ipbest) {
             
            log.info( "api index params.ip = ${params.ip}") 
            def iplog = cacheService.checkIP(params.ip)
            params.ipbest = iplog.last
        }
        // 开始返回task
        log.info( "api index ip.last = ${params.ipbest}") 
        def actions = cacheService.giveTask(params.int("ipbest") , user.id)
        
        log.info( "api index actions size = ${actions.size()}") 
        if (params.int("ipbest") > 24) {
             user.total += actions.size() * 10
        }else{
             user.total += actions.size() 
        } 
        if( !user.save() ) {
           user.errors.each {
                log.info it
           }
        }

        if (actions.size() < CacheService.RETURN_TOTAL) {
            params.ipbest = '-1'
            cacheService.syncPerUser(user.id)
        }

def result = """{"ipbest" : ${params.ipbest} ,
"task" : "${actions.join('||')}",
"token": "${params.t}"}"""

        //render( result)  
        render(
            contentType:"text/json",
            text : result)  
    }


    static String version = "云精英联盟 1.0";
    static String updateURL = "";

    def update = {
       render( "${ApiController.version}|${ApiController.updateURL}")
    }

    def test = {
        cacheService.testTask()
        cacheService.testUserLog()
        cacheService.testIP()
        
        render("OK")
    }
}
